import React, { useState, useRef, useEffect } from 'react';
import { SearchOutlined, FilterOutlined, DownOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Radio, Popconfirm, Select, Tooltip, Dropdown, Divider } from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import RcViewer from '@hanyk/rc-viewer';
import { Resizable } from 'react-resizable';
import 'react-resizable/css/styles.css';

import { useLatest } from 'ahooks';
import { Editor } from 'tinymce';
const { Search } = Input;
var storage = window.localStorage;

// 可伸缩的表头组件
const ResizableTitle = props => {
  const { onResize, width, onResizeStop, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className="react-resizable-handle"
          onClick={e => e.stopPropagation()}
          style={{
            position: 'absolute',
            right: -5,
            bottom: 0,
            top: 0,
            width: 10,
            cursor: 'col-resize'
          }}
        />
      }
      onResize={onResize}
      onResizeStop={onResizeStop}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

/**
 * 精简版可伸缩表格组件，专门针对左右分栏布局优化
 * @param {Object} showCz  操作区对象  showCz.showEdit 是否显示编辑 showCz.showView 是否显示查看 showCz.showDelete 是否显示删除
 * @param {Number} czWidth  操作区的宽度 默认100
 * @param {function} handleEdit  编辑或查看的回调方法
 * @param {function} handleDelete  删除的回调方法
 * @param {function} renderCz  操作区的渲染组件 
 * @param {function} handleView  查看的回调方法
 * @param {function} rowCz  行操作条件 返回一个对象，对象的key为操作名，value为操作的回调方法 传了rowCz则showCz无效
 * @param {Object} czMaps  操作区的map对象
 * @returns 
 */
const ResizableTableMin = (props) => {
  const history = useHistory();
  const [selectionType, setSelectionType] = useState(props.selecttype ? props.selecttype : 'checkbox');
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [currentdatas, setcurrentdatas] = useState([])
  const [isExactMatch, setIsExactMatch] = useState(false);
  const [columns, setColumns] = useState([]);
  const columnsRef = useLatest(columns);

  const isExactMatchRef = useLatest(isExactMatch);
  
  useEffect(() => {
    setColumns(
      props.tablecolnum.filter(item => item.show == true).map((item) => ({
        ...item,
        dataIndex: item.key,
        onHeaderCell: column => ({
          width: column.width,
          onResize: handleResize(item.key),
          onResizeStop: handleResizeStop(item.key),
        }),
        ...getColumnSearchProps(item.key, item.style, item.rendertype, item.ifcolor, item.title, item.searchtype),
      }))
    )
  }, [props.tablecolnum])

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    selectedRowKeys: props.selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      props.handleselectson(selectedRows, selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(false);
  };

  const handleSearchExact = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(true);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  //row双击
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {
        if (props.sfdoubleclick) {
          storage[props.storagekey] = JSON.stringify(record)
          history.push({ pathname: props.doubleclickroute });
        }
      }
    }
  };

  const handleResize = (dataIndex) => (e, { size }) => {
    setColumns(prevColumns => {
      return prevColumns.map(col => {
        if (col.dataIndex === dataIndex) {
          return {
            ...col,
            width: size.width,
          };
        }
        return col;
      });
    });
  };

  const handleResizeStop = (key) => (e, { size }) => {
    storage[props.storageName] = JSON.stringify(columnsRef.current.filter(item => item.dataIndex != "action"))
  };

  const components = {
    header: {
      cell: ResizableTitle,
    },
  };

  // 精简版搜索属性
  const getColumnSearchProps = (dataIndex, style, rendertype, ifcolor, title, searchtype) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 8,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        <Input
          ref={searchInput}
          placeholder={`搜索 ${title}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#1890ff' : undefined,
        }}
      />
    ),
    onFilter: (value, record) => {
      const text = record[dataIndex];
      if (!text) return false;
      
      if (isExactMatchRef.current) {
        return text.toString().toLowerCase() === value.toLowerCase();
      }
      
      return text.toString().toLowerCase().includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text, rendertype) => {
      const isMatch = searchedColumn === dataIndex && searchText;
      
      if (rendertype === 'image') {
        return (
          <span>
            {isMatch ? (
              <Highlighter
                highlightStyle={{
                  backgroundColor: '#ffc069',
                  padding: 0,
                }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text ? text.toString() : ''}
              />
            ) : (
              <RcViewer>
                <img src={text} alt="图片" style={{ width: '50px', height: '50px', objectFit: 'cover' }} />
              </RcViewer>
            )}
          </span>
        );
      }

      if (rendertype === 'html') {
        return (
          <span>
            {isMatch ? (
              <Highlighter
                highlightStyle={{
                  backgroundColor: '#ffc069',
                  padding: 0,
                }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text ? text.toString() : ''}
              />
            ) : (
              <div dangerouslySetInnerHTML={{ __html: text }} />
            )}
          </span>
        );
      }

      if (rendertype === 'link') {
        return (
          <span>
            {isMatch ? (
              <Highlighter
                highlightStyle={{
                  backgroundColor: '#ffc069',
                  padding: 0,
                }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text ? text.toString() : ''}
              />
            ) : (
              <a href={text} target="_blank" rel="noopener noreferrer" style={{ color: '#1890ff' }}>
                {text}
              </a>
            )}
          </span>
        );
      }

      if (rendertype === 'color') {
        return (
          <span>
            {isMatch ? (
              <Highlighter
                highlightStyle={{
                  backgroundColor: '#ffc069',
                  padding: 0,
                }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text ? text.toString() : ''}
              />
            ) : (
              <span style={style ? style : {}}>{text}</span>
            )}
          </span>
        );
      }

      if (rendertype === 'tooltip') {
        return (
          <span>
            {isMatch ? (
              <Highlighter
                highlightStyle={{
                  backgroundColor: '#ffc069',
                  padding: 0,
                }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text ? text.toString() : ''}
              />
            ) : (
              <Tooltip title={text}>
                <span style={style ? style : {}}>{text}</span>
              </Tooltip>
            )}
          </span>
        );
      }

      return (
        <span>
          {isMatch ? (
            <Highlighter
              highlightStyle={{
                backgroundColor: '#ffc069',
                padding: 0,
              }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          ) : (
            <span style={style ? style : {}}>{text}</span>
          )}
        </span>
      );
    },
  });

  // 精简版操作区组件
  const CzItems = (czProps) => {
    let czMaps = {}
    if (props.czMaps) {
      for (var key in props.czMaps) {
        czMaps[key] = { cz: props.czMaps[key].cz, handle: props[props.czMaps[key].handle] }
      }
    } else {
      czMaps = {
        showEdit: { cz: '编辑', handle: props.handleEdit },
        showDelete: { cz: '删除', handle: props.handleDelete },
        showView: { cz: '查看', handle: props.handleView },
      }
    }

    if (czProps.rowCz) {
      let keys = Object.keys(czProps.rowCz(czProps.record))
      if (keys.length == 1) {
        return keys.map(key => (
          <a key={key} onClick={() => czMaps[key].handle(czProps.record)} 
             style={{ fontSize: '0.75rem', color: '#1890ff', cursor: 'pointer' }}>
            {czMaps[key].cz}
          </a>
        ))
      } else if (keys.length > 1) {
        return <>
          <a key="1" onClick={() => czMaps[keys[0]].handle(czProps.record)} 
             style={{ fontSize: '0.75rem', color: '#1890ff', cursor: 'pointer' }}>
            {czMaps[keys[0]].cz}
          </a>
          <Divider type="vertical" />
          <Dropdown
            menu={{
              items: keys.map((key, index) => (index > 0 ? {
                key: key,
                label: <a onClick={() => czMaps[keys[index]].handle(czProps.record)} 
                          style={{ fontSize: '0.75rem', color: '#1890ff', cursor: 'pointer' }}>
                  {czMaps[keys[index]].cz}
                </a>
              } : ''))
            }}
          >
            <a onClick={(e) => e.preventDefault()} 
               style={{ fontSize: '0.7rem', color: '#1890ff', cursor: 'pointer' }}>
              <Space>
                更多
                <DownOutlined />
              </Space>
            </a>
          </Dropdown>
        </>
      } else {
        return ''
      }
    } else {
      if (czProps.showCz) {
        let keys = Object.keys(czProps.showCz)
        if (keys.length == 1) {
          return keys.map(key => (
            <a key={key} onClick={() => czMaps[key].handle(czProps.record)} 
               style={{ fontSize: '0.75rem', color: '#1890ff', cursor: 'pointer' }}>
              {czMaps[key].cz}
            </a>
          ))
        } else if (keys.length > 1) {
          return <>
            <a key="1" onClick={() => czMaps[keys[0]].handle(czProps.record)} 
               style={{ fontSize: '0.75rem', color: '#1890ff', cursor: 'pointer' }}>
              {czMaps[keys[0]].cz}
            </a>
            <Divider type="vertical" style={{ height: "1.8vw" }} />
            <Dropdown
              menu={{
                items: keys.map((key, index) => (index > 0 ? {
                  key: key,
                  label: <a onClick={() => czMaps[keys[index]].handle(czProps.record)} 
                            style={{ fontSize: '0.75rem', color: '#1890ff', cursor: 'pointer' }}>
                    {czMaps[keys[index]].cz}
                  </a>
                } : ''))
              }}
            >
              <a onClick={(e) => e.preventDefault()} 
                 style={{ fontSize: '0.7rem', color: '#1890ff', cursor: 'pointer' }}>
                <Space>
                  更多
                  <DownOutlined />
                </Space>
              </a>
            </Dropdown>
          </>
        } else {
          return ''
        }
      }
    }
  }

  // 添加操作列
  props.showCz && Object.keys(props.showCz).length > 0 && columns.filter(item => item.key == "action").length == 0 ?
    columns.push({
      title: '操作',
      dataIndex: 'action',
      fixed: "right",
      width: props.czWidth ? props.czWidth : 100, // 默认宽度改为100
      key: 'action',
      render: (text, record) => (
        props.renderCz ? props.renderCz(record) :
          <div style={{ width: "100%", display: "flex", justifyContent: "space-around" }}>
            <CzItems record={record} showCz={props.showCz} rowCz={props.rowCz} />
          </div>
      )
    }) : ''

  return (
    <div style={{ position: "relative", height: "100%", width: props.width ? props.width : "100%" }}>
      <Radio.Group style={{ 
        display: props.ifhiddencchangeselecttype ? "none" : "block",
        marginBottom: "1rem"
      }}
        onChange={({ target: { value } }) => {
          setSelectionType(value);
        }}
        value={selectionType}
      >
        <Radio value="checkbox">多选</Radio>
        <Radio value="radio">单选</Radio>
      </Radio.Group>

      {props.title ? (
        <Table 
          columns={columns} 
          dataSource={props.tabledata} 
          style={{
            width: "100%", 
            height: "calc(100% - 3rem)"
          }}
          title={() => { return <div style={{ fontWeight: "400", fontSize: "14px" }}>{props.title}</div> }}
          size="small"
          pagination={{
            defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 15,
            total: currentdatas.length, 
            pageSizeOptions: ['15', '30', '50'], 
            position: ['bottomLeft']
          }}
          bordered={props.bordered ? props.bordered : false}
          onRow={onRowSelect}
          scroll={props.scroll ? props.scroll : { x: 'max-content', y: 'calc(100vh - 300px)' }}
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }}
          className="custom-table-styles" 
        />
      ) : (
        <Table 
          columns={columns} 
          dataSource={props.tabledata} 
          style={{
            width: "100%", 
            height: "calc(100% - 3rem)"
          }}
          size="small"
          pagination={{
            defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 15,
            total: currentdatas.length, 
            pageSizeOptions: ['15', '30', '50'],
            position: ['bottomLeft']
          }}
          expandable={props.expandable ? props.expandable : {}}
          bordered={props.bordered ? props.bordered : false}
          scroll={props.scroll ? props.scroll : { x: 'max-content', y: 'calc(100vh - 300px)' }}
          onChange={(pagination, filters, sorter, extra) => {
            setcurrentdatas(extra.currentDataSource)
          }}
          rowClassName={props.rowClassName ? (record, index) => { return props.rowClassName(record, index) } : ''}
          components={components}
          onRow={onRowSelect}
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }}
          className="custom-table-styles" 
        />
      )}
    </div>
  )
}

export default ResizableTableMin 